<?php

include "models/user.php";
include "models/risposta.php";


$error = "";

//---- Variabili utilizzate per inizializzare il form in entrata ---//
$page = $_POST['page'];

$risp1 = $_POST["risp1"];
$risp2 = $_POST["risp2"];
$risp3 = $_POST["risp3"];
$risp4 = $_POST["risp4"];
$risp5 = $_POST["risp5"];
$note = $_POST["note"];
//------------------------------ ---//



function stripslashes_deep($value){
  $value = is_array($value) ? array_map("stripslashes_deep", $value) : stripslashes($value);
	return $value;
}

function  isChecked($var){
	return ($var=="on" ? "checked" : "");
	
}
$api = null;
try
{
	// Are we running in development or production mode? You can easily switch
	// between these two in the Apache VirtualHost configuration.
//	if (!defined('APPLICATION_ENV'))
//		define('APPLICATION_ENV', getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production');

	define( 'APPLICATION_ENV', 'development');
	
	$_POST = array_map("stripslashes_deep", $_POST);
	
	// In development mode, we show all errors because we obviously want to 
	// know about them. We don't do this in production mode because that might
	// expose critical details of our app or our database. Critical PHP errors
	// will still be logged in the PHP and Apache error logs, so it's always
	// a good idea to keep an eye on them.
	if (APPLICATION_ENV == 'development')
	{
		error_reporting(E_ALL|E_STRICT);
		ini_set('display_errors', 'off');
	}
	else
	{
		error_reporting(0);
		ini_set('display_errors', 'off');
	}

	// Load the config file. I prefer to keep all configuration settings in a
	// separate file so you don't have to mess around in the main code if you
	// just want to change some settings.
	require_once 'lib/api_config.php';
	$config = $config[APPLICATION_ENV];

	// In development mode, we fake a delay that makes testing more realistic.
	// You're probably running this on a fast local server but in production
	// mode people will be using it on a mobile device over a slow connection.
//	if (APPLICATION_ENV == 'development')
//		sleep(2);

	// To keep the code clean, I put the API into its own class. Create an
	// instance of that class and let it handle the request.
	global $api;
	$api = new API($config);
	$api->handleCommand();

//	echo "OK" . PHP_EOL;
}
catch (Exception $e)
{
	// The code throws an exception when something goes horribly wrong; e.g.
	// no connection to the database could be made. In development mode, we
	// show these exception messages. In production mode, we simply return a
	// "500 Server Error" message.

	if (APPLICATION_ENV == 'development')
		var_dump($e);
	else
		exitWithHttpError(500);
}


function writeToLog($message)
{
	global $config;
	if ($fp = fopen($config['logfile'], 'at'))
	{
		fwrite($fp, date('c') . ' ' . $message . PHP_EOL);
		fclose($fp);
	}
}

////////////////////////////////////////////////////////////////////////////////

function exitWithHttpError($error_code, $message = '')
{
	switch ($error_code)
	{
		case 400: header("HTTP/1.0 400 Bad Request"); break;
		case 403: header("HTTP/1.0 403 Forbidden"); break;
		case 404: header("HTTP/1.0 404 Not Found"); break;
		case 500: header("HTTP/1.0 500 Server Error"); break;
	}

	header('Content-Type: text/plain');

	if ($message != '')
		header('X-Error-Description: ' . $message);

	exit;
}

function isValidUtf8String($string, $maxLength, $allowNewlines = false)
{
	if (empty($string) || strlen($string) > $maxLength)
		return false;

	if (mb_check_encoding($string, 'UTF-8') === false)
		return false;

	// Don't allow control characters, except possibly newlines	
	for ($t = 0; $t < strlen($string); $t++)
	{
		$ord = ord($string{$t});

		if ($allowNewlines && ($ord == 10 || $ord == 13))
			continue;

		if ($ord < 32)
			return false;
	}

	return true;
}

function truncateUtf8($string, $maxLength)
{
	$origString = $string;
	$origLength = $maxLength;

	while (strlen($string) > $origLength)
	{
		$string = mb_substr($origString, 0, $maxLength, 'utf-8');
		$maxLength--;
	}

	return $string;
}


////////////////////////////////////////////////////////////////////////////////

class API
{
	// Because the payload only allows for 256 bytes and there is some overhead
	// we limit the message text to 190 characters.
	const MAX_MESSAGE_LENGTH = 190;

	public  $pdo;

	function __construct($config)
	{
		// Create a connection to the database.
		$this->pdo = new PDO(
			'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], 
			$config['db']['username'], 
			$config['db']['password'],
			array());

		// If there is an error executing database queries, we want PDO to
		// throw an exception. Our exception handler will then exit the script
		// with a "500 Server Error" message.
		$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		// We want the database to handle all strings as UTF-8.
		$this->pdo->query('SET NAMES utf8');
	}

	function handleCommand()
	{
		// Figure out which command the client sent and let the corresponding
		// method handle it. If the command is unknown, then exit with an error
		// message.
		if (isset($_GET['cmd']))
			$_POST['cmd'] = $_GET['cmd'];
			
		if (isset($_POST['cmd']))
		{
			switch (trim($_POST['cmd']))
			{
				case 'login': $this->login(); return;
				case 'registra': $this->registra(); return;
				case 'submit': $this->submit(); return;
				case 'logout': $this->logout(); return;
				case 'get_resp': $this->getResponse(); return;
				case 'statistiche': $this->getStatistiche(); return;
				case 'setrole': $this->setRole(); return;
			}
		}else {
			$this->normalRquest(); return;
		}

		exitWithHttpError(400, 'Unknown command');
	}

	function normalRquest(){
		
		if (isset($_POST["page"])){
			//if ($this->checkResponse()) {//Se tutto ok
				//Salvo la risposta
				$res = $this->saveResponse();
				if ($res["success"] == true) {
					header("HTTP/1.1 200 OK");
					header("location:".($_POST["page"]+1).".php");	
				}else {
					header("location:".($_POST["page"]).".php?error=".urlencode($res[1]));
				}
			/*}else{
				
				
			}*/
		}
	}
	
	function setRole(){
		$admin = $_GET["admin"];
		$currentUser = $_GET["currentUser"];
		
		$usr = new user($this->pdo);
		
		$users = array();
		$res= $usr->setRole($currentUser, $admin);
		
		print json_encode($res);
	}
	
	function getStatistiche(){
		$risposta = new risposta($this->pdo);
		
		$res = $risposta->getStatistiche();
		
		$result = array();
		
		foreach ($res as $r){
			array_push($result, 
				array(
					"risp1"=>$r['ris1'],
					"risp2"=>$r['ris2'],
					"risp3"=>$r['ris3'],
					"risp4"=>$r['ris4'],
					"risp5"=>$r['ris5'],
					"num_slide"=>$r['num_slide']
				)
			);
		}
		
		print  json_encode($result);
	}
	
	function getResponse(){
		session_start();
		$risposta = new risposta($this->pdo);
		
		$username = $_SESSION['login_user'];
		
		if ($username) {
			$page = $_GET['page'];
			
			$res = $risposta->getResp($username, $page);
			
			$result = array();
			foreach ($res as $c){
				$result = array(
					"risp1"=>$c['risp1'],
					"risp2"=>$c['risp2'],
					"risp3"=>$c['risp3'],
					"risp4"=>$c['risp4'],
					"risp5"=>$c['risp5'],
					"nota"=>$c['nota']
				);
			}
			
			print  json_encode($result);
		}
		
	}
	
	
	function saveResponse(){
		session_start();
		$username = $_SESSION['login_user']; 
		
		$risposta = new risposta($this->pdo);
		
		if ($username) {
			return  $risposta->saveResp($username);
		}
		
	}
	
	/*function  checkResponse(){
		global $error;
		$c = 0;
		
		if (isset($_POST["risp1"])) {
			for ($i = 1; $i < 5; $i++) {
				if ($_POST["risp".$i] == "on") {
					$c++;
				}
			}
			
			if ($c > 1) {
				$error = "Risposte multiple non consentite";
				return false;
			}
			
			if ($_POST['page']!=null && $c==0) {
				$error = "Risposta obbligatoria";
				return false;
			}
		}
		
		return true;
	}*/
	
	

	function login(){
		session_start();
		
		$msg = "";
	
		$username=$_POST['username']; 
		$password=$_POST['password']; 

		$usr = new user($this->pdo);
		
		$users = array();
		$utenti= $usr->checkUser($username, $password);
		
		foreach ($utenti as $u){
			array_push($users, $u);
		}
		
		if(count($users)==0){
			$resp = array("success"=>false, "msg"=>"Username o Password errate");
			print json_encode($resp);
			exit();
		} else if(count($users)==1){
			session_start();
			$_SESSION['login_user']=$username;
			$_SESSION['admin'] = $users[0]["admin"];
			//header("HTTP/1.1 200 OK");
			//header("location: index.php");
			$resp = array("success"=>true);
			print json_encode($resp);
		}
	}
	
	function logout(){
		session_start();
		$_SESSION['login_user']=null;
		session_destroy();
	}
	
	
	function registra(){
		$msg = "";
		session_start();
		$usr = new user($this->pdo);
		
		$username=$_POST['username'];
		$res = $usr->registra();
		
		if (!$res["success"] == true) {
			header("HTTP/1.1 200 OK");
			header("location: pages/registra.php?error=".urlencode($res["msg"]));
			//$resp = array("success"=>true);
			//print   json_encode($resp);
			return "true";
			
		}else {
			$_SESSION['login_user']=$username;
			//Registrazione ok
			header("HTTP/1.1 200 OK");
			header("location: slide/1.php");
			//$resp = array("success"=>false, "msg"=>urlencode($res["msg"]));
			//print  "false"."|".$res["msg"];
		}
		
	}
	
	
	
	
	
	
	
	
}
